package com.dsm.alilinkvisualappdemo

import android.content.Context
import android.text.TextUtils
import com.dwy.dsmhttp.core.RequestHandler
import com.dwy.log.LogManager
import com.hjq.http.EasyConfig
import com.hjq.http.EasyUtils
import com.hjq.http.config.IHttpLogStrategy
import com.hjq.http.config.IRequestServer
import okhttp3.OkHttpClient

object AppHttpManager {

    private val tagName = AppHttpManager::class.java.simpleName

    fun init(context: Context) {
        val okHttpClient: OkHttpClient = OkHttpClient.Builder()
            .build()

        EasyConfig.with(okHttpClient)
            // 是否打印日志
            .setLogEnabled(BuildConfig.DEBUG)
            .setLogStrategy(object : IHttpLogStrategy{
                override fun printLog(tag: String, log: String) {
                    LogManager.iLog.logd(tagName + "_" + tag, log)
                }

                override fun printJson(tag: String, json: String) {
                    var text = EasyUtils.formatJson(json)
                    if (TextUtils.isEmpty(text)) {
                        return
                    }

                    // 打印 Json 数据最好换一行再打印会好看一点
                    text = " \n$text"

                    val segmentSize = 3 * 1024
                    val length = text.length.toLong()
                    if (length <= segmentSize) {
                        // 长度小于等于限制直接打印
                        printLog(tag, text)
                        return
                    }

                    // 循环分段打印日志
                    while (text.length > segmentSize) {
                        val logContent = text.substring(0, segmentSize)
                        text = text.replace(logContent, "")
                        printLog(tag, logContent)
                    }

                    // 打印剩余日志
                    printLog(tag, text)
                }

                override fun printKeyValue(tag: String, key: String, value: String) {
                    printLog(tag, "$key = $value")
                }

                override fun printThrowable(tag: String, throwable: Throwable) {
                    printLog(tag, throwable.stackTraceToString())
                }

                override fun printStackTrace(tag: String, stackTrace: Array<out StackTraceElement>) {
                    for (element in stackTrace) {
                        // 获取代码行数
                        val lineNumber = element.lineNumber
                        // 获取类的全路径
                        val className = element.className
                        if (lineNumber <= 0 || className.startsWith("com.hjq.http")) {
                            continue
                        }
                        printLog(tag, "RequestCode = (" + element.fileName + ":" + lineNumber + ") ")
                        break
                    }
                }

            })
            // 设置服务器配置（必须设置）
            .setServer(RequestServer())
            // 设置请求处理策略（必须设置）
            .setHandler(RequestHandler(context))
            // 设置请求重试次数
            .setRetryCount(3) // 添加全局请求参数
            //.addParam("token", "6666666")
            // 添加全局请求头
            //.addHeader("time", "20191030")
            // 启用配置
            .into()
    }

    fun addHeader(key: String, value: String) {
        EasyConfig.getInstance().addHeader(key, value)
    }

    fun updateServerUrl(serverUrl: String) {
        EasyConfig.getInstance().setServer(serverUrl)
    }

    fun updateHttpToken(token: String) {
        addHeader("token", token)
        addHeader("phoneType", "Android")
        addHeader("language", "1")
        addHeader("clientType", "ANDROID")
    }

    private class RequestServer : IRequestServer {
        override fun getHost(): String {
            /*return "http://192.168.1.74:8081"*/
            return "https://nyuwa.dsmxp.com"
        }
    }
}